package com.hua.zhifubao;

import android.util.Log;

public class SnowflakeIdGenerator {
    private static final long START_EPOCH = 1609459200000L; // 2021-01-01 00:00:00
    private static final long MACHINE_ID_BITS = 5L;
    private static final long SEQUENCE_BITS = 15L;
    private static final long MAX_MACHINE_ID = ~(-1L << MACHINE_ID_BITS);
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);
    private long machineId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public SnowflakeIdGenerator(long machineId) {
        if (machineId > MAX_MACHINE_ID || machineId < 0) {
            throw new IllegalArgumentException("Machine ID can't be greater than " + MAX_MACHINE_ID + " or less than 0");
        }
        this.machineId = machineId;
    }

    public synchronized String nextId() {
        long timestamp = System.currentTimeMillis();
        // 检查时间戳是否回退
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate ID");
        }
        if (lastTimestamp == timestamp) {
            // 如果在同一毫秒内，增加序列号
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                // 序列号达到最大值，需要等待下一毫秒
                timestamp = waitNextMillis(lastTimestamp);
            }
        } else {
            // 不同毫秒，重置序列号
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        long uniqueId = ((timestamp - START_EPOCH) << (MACHINE_ID_BITS + SEQUENCE_BITS)) | (machineId << SEQUENCE_BITS) | sequence;
        Log.d("uniqueId = ", String.valueOf(uniqueId));
        String idStr = String.valueOf(uniqueId).substring(0, 18);
        return idStr;
    }

    private long waitNextMillis(long lastTimestamp) {
        long timestamp;
        try {
            while ((timestamp = System.currentTimeMillis()) <= lastTimestamp) {
                Thread.sleep(1);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while waiting for next millisecond", e);
        }
        return timestamp;
    }

    private String toBase36(long id) {
        return Long.toString(id, 36);
    }
}
